#ifndef DATAVIEW_H
#define DATAVIEW_H

#include "mavlink/common/mavlink.h"
#include <iostream>
#include <mutex>
#include <QWidget>
#include <QTableWidget>
#include <QVBoxLayout>
#include <QString>
#include <QCheckBox>
#include <QLabel>
#include <QHBoxLayout>

struct MissionHeartbeat1hz_t {
    int64_t seq{0};
    uint8_t drone_type;   // 飞机类型 DroneType
    uint8_t drone_id;   // 飞机id
    uint8_t fcs_flight_mode;  // 飞行模式FlightControlMode
    bool fcs_arm;   // 

    uint8_t smart_mode;         // 飞机工作模式，主模式
    uint8_t smart_mode_status;  // 工作状态

    bool is_home_invalid;  // home点无效
    double home_x_lat; // home点纬度 = 
    double home_y_lon; // home点经度 = 
    double home_z_alt; // home点高度 = 
    double backup_home_lat;             // 备降点0纬度 = 
    double backup_home_lon;             // 备降点0经度 = 
    double backup_home_alt;             // 备降点0高度 = b
    bool backup_home_valid;              // 备降点有效：TRUE
};

struct MissionHeartbeat5hz_t {
    int64_t seq{0};
    uint8_t drone_type;   // 飞机类型 DroneType
    uint8_t drone_id;   // 飞机id
    bool is_gps_invalid;  // home点无效
    double uav_lat; // uav纬度
    double uav_lon; // home点经度 =
    double uav_alt; // home点高度 
    int32_t gps_num;  // 卫星数
    int32_t gps_fix;  // 定位状态

    double roll;  // 滚转角
    double pitch;  // 俯仰角
    double yaw;  // 航向角
    double position[3];  // 位置
    double velocity[3];  // 速度
    double distance_m;  // 飞行距离
};

struct ItemData_t
{
    MissionHeartbeat1hz_t heartbeat1hz;
    MissionHeartbeat5hz_t heartbeat5hz;
};


class DataItem : public QWidget
{
    Q_OBJECT

public:
    DataItem(const int drone_type, const int drone_id, const MissionHeartbeat5hz_t data, QWidget *parent = nullptr);
    DataItem(const int drone_type, const int drone_id, const MissionHeartbeat1hz_t data, QWidget *parent = nullptr);
    void update(const MissionHeartbeat1hz_t &msg);
    void update(const MissionHeartbeat5hz_t &msg);
    
    bool isChecked();
    int getDroneType();
    int getDroneId();

private:
    uint8_t drone_type_{0};   // 飞机类型 DroneType
    uint8_t drone_id_{0};   // 飞机id
    ItemData_t data_;
    std::mutex data_mtx_;

    QCheckBox *checkBox_;
    QLabel *sequenceLabel_;
    QLabel *connectionStateLabel_;
    QLabel *locationInfoLabel_;
    QLabel *statusInfoLabel_;

    void initView();
    void updateView();
    QString getPosStr();
    QString getStatusStr();
    
};

class DataView : public QWidget
{
    Q_OBJECT

public:
    DataView(QWidget *parent = nullptr);

    void updateData(const QList<DataItem> &dataItems);

public slots:
    void receiveMsgSlot(const mavlink_message_t& message);
private:
    QTableWidget *tableWidget;

    int updateHB(const mavlink_mission_heartbeat_1hz_t &msg);
    int updateHB(const mavlink_mission_heartbeat_5hz_t &msg);

    void addNewTableUav(const mavlink_mission_heartbeat_1hz_t &msg);
    void addNewTableUav(const mavlink_mission_heartbeat_5hz_t &msg);
};

#endif // DATAVIEW_H